<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center">
        <button @click="$router.back()" class="mr-4 p-2 text-gray-500 hover:text-gray-700 focus:outline-none">
          <ArrowLeftIcon class="h-6 w-6" />
        </button>
        <h2 class="text-2xl font-semibold text-gray-800">设备详情</h2>
      </div>
      <div class="flex space-x-3">
        <button @click="editEquipment" class="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
          <PencilIcon class="h-5 w-5 mr-2" />
          编辑设备
        </button>
        <button @click="borrowEquipment" v-if="equipment && equipment.status === 'NORMAL'" class="flex items-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2">
          <HandRaisedIcon class="h-5 w-5 mr-2" />
          借用设备
        </button>
      </div>
    </div>

    <div v-if="loading" class="text-center py-8">
      <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
      <p class="mt-2 text-gray-500">加载中...</p>
    </div>

    <div v-else-if="equipment" class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- 设备基本信息 -->
      <div class="lg:col-span-2">
        <div class="bg-white rounded-xl shadow-lg p-6">
          <h3 class="text-xl font-semibold text-gray-800 mb-4">基本信息</h3>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-500">设备编号</label>
              <p class="mt-1 text-sm text-gray-900">{{ equipment.code }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">设备名称</label>
              <p class="mt-1 text-sm text-gray-900">{{ equipment.name }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">设备类别</label>
              <p class="mt-1 text-sm text-gray-900">{{ equipment.category }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">设备状态</label>
              <span :class="['mt-1 inline-flex px-2 py-1 text-xs font-semibold rounded-full', getStatusClass(equipment.status)]">
                {{ getStatusText(equipment.status) }}
              </span>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">规格型号</label>
              <p class="mt-1 text-sm text-gray-900">{{ equipment.specification }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">数量</label>
              <p class="mt-1 text-sm text-gray-900">{{ equipment.quantity }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">单价</label>
              <p class="mt-1 text-sm text-gray-900">¥{{ equipment.unitPrice }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">总价值</label>
              <p class="mt-1 text-sm text-gray-900">¥{{ (equipment.unitPrice * equipment.quantity).toLocaleString() }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">生产厂家</label>
              <p class="mt-1 text-sm text-gray-900">{{ equipment.manufacturer }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">购置日期</label>
              <p class="mt-1 text-sm text-gray-900">{{ equipment.purchaseDate }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">保修期</label>
              <p class="mt-1 text-sm text-gray-900">{{ equipment.warranty || '无' }}</p>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-500">经手人</label>
              <p class="mt-1 text-sm text-gray-900">{{ equipment.handler || '未设置' }}</p>
            </div>
          </div>
        </div>

        <!-- 维修记录 -->
        <div class="bg-white rounded-xl shadow-lg p-6 mt-6">
          <h3 class="text-xl font-semibold text-gray-800 mb-4">维修记录</h3>
          <div v-if="repairRecords.length === 0" class="text-center py-8 text-gray-500">
            暂无维修记录
          </div>
          <div v-else class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50">
                <tr>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">维修日期</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">故障描述</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">维修厂家</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">维修费用</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">责任人</th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <tr v-for="record in repairRecords" :key="record.id">
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ record.repairDate }}</td>
                  <td class="px-6 py-4 text-sm text-gray-900">{{ record.faultDescription }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ record.repairManufacturer }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">¥{{ record.repairCost }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ record.responsiblePerson }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- 右侧信息 -->
      <div class="space-y-6">
        <!-- 借用记录 -->
        <div class="bg-white rounded-xl shadow-lg p-6">
          <h3 class="text-xl font-semibold text-gray-800 mb-4">最近借用记录</h3>
          <div v-if="borrowRecords.length === 0" class="text-center py-4 text-gray-500">
            暂无借用记录
          </div>
          <div v-else class="space-y-3">
            <div v-for="record in borrowRecords" :key="record.id" class="border-l-4 border-indigo-400 pl-4 py-2">
              <div class="flex justify-between items-start">
                <div>
                  <p class="text-sm font-medium text-gray-900">{{ record.borrowerName }}</p>
                  <p class="text-xs text-gray-500">{{ record.borrowDate }}</p>
                </div>
                <span :class="['px-2 py-1 text-xs font-semibold rounded-full', getBorrowStatusClass(record.status)]">
                  {{ getBorrowStatusText(record.status) }}
                </span>
              </div>
              <p v-if="record.expectedReturnDate" class="text-xs text-gray-500 mt-1">
                预计归还：{{ record.expectedReturnDate }}
              </p>
            </div>
          </div>
        </div>

        <!-- 设备图片 -->
        <div class="bg-white rounded-xl shadow-lg p-6">
          <h3 class="text-xl font-semibold text-gray-800 mb-4">设备图片</h3>
          <div v-if="equipment.imageUrl" class="text-center">
            <img :src="equipment.imageUrl" :alt="equipment.name" class="w-full h-48 object-cover rounded-lg">
          </div>
          <div v-else class="text-center py-8 text-gray-500">
            <PhotoIcon class="h-12 w-12 mx-auto mb-2 text-gray-300" />
            <p>暂无设备图片</p>
          </div>
        </div>

      </div>
    </div>

    <div v-else class="text-center py-8">
      <ExclamationTriangleIcon class="h-12 w-12 mx-auto text-gray-400 mb-4" />
      <p class="text-gray-500">设备信息不存在</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  ArrowLeftIcon,
  PencilIcon,
  HandRaisedIcon,
  PhotoIcon,
  ExclamationTriangleIcon,
} from '@heroicons/vue/24/outline'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const equipment = ref(null)
const repairRecords = ref([])
const borrowRecords = ref([])

// 获取设备详情
const loadEquipmentDetail = async () => {
  try {
    loading.value = true
    const equipmentId = route.params.id
    
    // 调用真实API加载设备详情
    const response = await request.get(`/equipment/${equipmentId}`)
    equipment.value = response.data
    
    // 加载维修记录
    try {
      const repairResponse = await request.get(`/equipment-repair/list?equipmentId=${equipmentId}`)
      repairRecords.value = repairResponse.data.records || []
    } catch (error) {
      console.error('加载维修记录失败:', error)
      repairRecords.value = []
    }
    
    // 加载借用记录
    try {
      const borrowResponse = await request.get(`/equipment-borrow/list?equipmentId=${equipmentId}`)
      borrowRecords.value = borrowResponse.data.records || []
    } catch (error) {
      console.error('加载借用记录失败:', error)
      borrowRecords.value = []
    }
    
    
  } catch (error) {
    console.error('加载设备详情失败:', error)
    showMessage('加载设备详情失败', 'error')
  } finally {
    loading.value = false
  }
}

// 获取状态样式
const getStatusClass = (status) => {
  const statusMap = {
    'NORMAL': 'bg-green-100 text-green-800',
    'BORROWED': 'bg-yellow-100 text-yellow-800',
    'REPAIRING': 'bg-blue-100 text-blue-800',
    'SCRAPPED': 'bg-red-100 text-red-800'
  }
  return statusMap[status] || 'bg-gray-100 text-gray-800'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'NORMAL': '正常',
    'BORROWED': '借用中',
    'REPAIRING': '维修中',
    'SCRAPPED': '已报废'
  }
  return statusMap[status] || status
}

// 获取借用状态样式
const getBorrowStatusClass = (status) => {
  const statusMap = {
    'BORROWED': 'bg-yellow-100 text-yellow-800',
    'RETURNED': 'bg-green-100 text-green-800',
    'OVERDUE': 'bg-red-100 text-red-800'
  }
  return statusMap[status] || 'bg-gray-100 text-gray-800'
}

// 获取借用状态文本
const getBorrowStatusText = (status) => {
  const statusMap = {
    'BORROWED': '借用中',
    'RETURNED': '已归还',
    'OVERDUE': '已超期'
  }
  return statusMap[status] || status
}

// 编辑设备
const editEquipment = () => {
  router.push(`/equipment/form/${equipment.value.id}`)
}

// 借用设备
const borrowEquipment = () => {
  router.push(`/equipment-borrow/form?equipmentId=${equipment.value.id}`)
}


// 简单消息显示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

onMounted(() => {
  loadEquipmentDetail()
})
</script>